package br.gerador;

import java.lang.reflect.Field;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import br.annotations.Coluna;
import br.factory.parametro.FactoryParametro;
import br.interfaces.Persistente;


public abstract class GerarSelect {

	public static String gerarSql(String tabela, List<String> colunas, List<Where> valores) {
		try {
			StringBuilder select = new StringBuilder();
			select.append("select ");
			for (String coluna : colunas) {
				select.append(coluna).append(", ");
			}
			select.delete(select.length()-2, select.length());
			select.append(" from ").append(tabela);
			if(valores != null && valores.size() > 0) {
				select.append(" where ");
				for (Where where : valores) {
					select.append(where.getCampo()).append(" ").append(where.getComparador()).append(" ? and ");
				}
				select.delete(select.length()-4, select.length());
			}

			return select.toString();
		} catch(Exception e) {
			e.printStackTrace();
			return null;
		}

	}

	public static List<Persistente> tratarRetorno(Persistente persistente, ResultSet rs) {
		List<Persistente> lista = new ArrayList<Persistente>();
		try {
			while(rs.next()) {
				Persistente p = persistente.getClass().newInstance();
				Field[] campos = persistente.getClass().getDeclaredFields();
				for (int i = 0; i < campos.length; i++) {
					Coluna coluna =  (Coluna) campos[i].getAnnotation(Coluna.class);
					if (coluna != null) {
						Object valor = campos[i].get(persistente);
						FactoryParametro.getInstance(campos[i].getType().getSimpleName()).getParametro(coluna.nome(), campos[i], p, rs);
					}
				}
				lista.add(p);
			}
			return lista;
		} catch(Exception e) {
			e.printStackTrace();
			return null;
		}
	}

}
